package cn.tongdun.atreus.common.log;

/**
 * @author wangze
 * @date 2021-10-19 13:25.
 **/


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;


/**
 * 日志工具类类
 * 脱敏
 *
 * @author wangze
 * @date 2021-10-19 13:14.
 **/
@Component
public class LoggerUtil {

	private static Map<String, Object> DRULES = new HashMap<>();

	@Autowired
	private JdbcService jdbcService;


	/**
	 * 首次加载，获取数据
	 */
	@PostConstruct
	public void init() {
		rules = "none";
		EXECUTE_RULES.clear();
		EXECUTE_RULES.addAll(getRuleFromDb());
		rules = EXECUTE_RULES.stream().map(x -> x.getField()).collect(Collectors.joining(","));
		for (LogConfig rule : EXECUTE_RULES) {
			DRULES.put(rule.getField(), "4,7");
		}
	}

	/**
	 * 正在执行的脱敏规则
	 */
	private static List<LogConfig> EXECUTE_RULES = new CopyOnWriteArrayList<>();

	private static String rules = "none";
	/**
	 * 更新脱敏规则
	 */
	static List<LogConfig> UPDATE_EXECUTE_RULES = new CopyOnWriteArrayList<>();
	/**
	 * 是否在更新
	 */
	public static volatile boolean IS_UPDATEING = false;

	public static Map<String, Object> getRules() {
		// 判断是否在定时更新
		if (IS_UPDATEING && UPDATE_EXECUTE_RULES != null) {
			synchronized (LoggerUtil.class) {
				if (IS_UPDATEING && UPDATE_EXECUTE_RULES != null) {
					EXECUTE_RULES.clear();
					EXECUTE_RULES.addAll(UPDATE_EXECUTE_RULES);
					for (LogConfig logConfig : EXECUTE_RULES) {
						DRULES.put(logConfig.getField(), "4,7");
					}
					IS_UPDATEING = false;
				}
			}
		}
		return DRULES;
	}

	public static String getRuleStr() {
		// 判断是否在定时更新
		if (IS_UPDATEING && UPDATE_EXECUTE_RULES != null) {
			synchronized (LoggerUtil.class) {
				if (IS_UPDATEING && UPDATE_EXECUTE_RULES != null) {
					EXECUTE_RULES.clear();
					EXECUTE_RULES.addAll(UPDATE_EXECUTE_RULES);
					rules = "none";
					rules = EXECUTE_RULES.stream().map(x -> x.getField()).collect(Collectors.joining(","));
					IS_UPDATEING = false;
				}
			}
		}
		return rules;
	}


	public List<LogConfig> getRuleFromDb() {
		return jdbcService.selectConfigList();

	}


}